package com.wll.exportfile.world;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class HtmlExportWorld {

    public static void main(String[] args) {
        String html = "<div>购买手机统计机型信息</div>" +
                "<table border='1' cellspacing='0' cellpadding='0'>" +
                "<tr>" +
                "<td>序号</td>" +
                "<td>型号</td>" +
                "<td>厂商</td>" +
                "<td>编码</td>" +
                "</tr>" +
                "<tr>" +
                "<td>1</td>" +
                "<td>P40</td>" +
                "<td>华为</td>" +
                "<td>100001</td>" +
                "</tr>" +
                "<tr>" +
                "<td>2</td>" +
                "<td>xiaomi8</td>" +
                "<td>小米</td>" +
                "<td>200001</td>" +
                "</tr>" +
                "</table>" +
                "<image src='C://Users//Administrator//Pictures//3.png'></image>" +
                "<image src='C://Users//Administrator//Pictures//3.png'></image>" +
                "<image src='C://Users//Administrator//Pictures//3.png'></image>";
        createWordForHtml(html, "手机采购");
    }

    /**
     * 将html代码导出为world
     *
     * @param html
     * @param fileName
     */
    public static void createWordForHtml(String html, String fileName) {
        try {
            String savePath = "E:/temp/" + System.currentTimeMillis() + "_" + fileName + ".doc";
            html = html.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&");
            String content = "<html><body>" + html + "</body></html>";
            //这里是必须要设置编码的，不然导出中文就会乱码。
            byte b[] = content.getBytes("GBK");
            //将字节数组包装到流中
            ByteArrayInputStream bais = new ByteArrayInputStream(b);
            /*
             * 关键地方
             * 生成word格式
             */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            OutputStream ostream = new FileOutputStream(savePath);
            //写入内容
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
